<template>
  <div class="banner-container">
    <el-carousel
      :height="height"
      :autoplay="autoplay"
      :interval="interval"
      :arrow="arrow"
      :indicator-position="indicatorPosition"
      @change="handleSlideChange"
    >
      <el-carousel-item v-for="banner in banners" :key="banner.id">
        <div
          class="banner-item"
          @click="handleBannerClick(banner)"
          :style="{ cursor: banner.linkUrl ? 'pointer' : 'default' }"
        >
          <img
            :src="banner.image"
            :alt="banner.title"
            class="banner-image"
            @error="handleImageError"
          />
        </div>
      </el-carousel-item>
    </el-carousel>

    <!-- 加载状态 -->
    <div v-if="loading" class="banner-loading">
      <el-skeleton animated>
        <template #template>
          <el-skeleton-item variant="image" :style="{ height: height }" />
        </template>
      </el-skeleton>
    </div>

    <!-- 空状态 -->
    <div v-if="!loading && banners.length === 0" class="banner-empty">
      <el-empty description="暂无轮播图" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, defineProps, defineEmits } from 'vue'
import { ElMessage } from 'element-plus'
import { bannerApi, type Banner } from '@/api/banner'
import { useRouter } from 'vue-router'

// Props
interface Props {
  position?: 1 | 2
  height?: string
  autoplay?: boolean
  interval?: number
  arrow?: 'always' | 'hover' | 'never'
  indicatorPosition?: 'outside' | 'none'
  showContent?: boolean
  limit?: number
}

const props = withDefaults(defineProps<Props>(), {
  position: 1,
  height: '400px',
  autoplay: true,
  interval: 4000,
  arrow: 'hover',
  indicatorPosition: 'outside',
  showContent: true,
  limit: 5
})

// Emits
const emit = defineEmits<{
  bannerClick: [banner: Banner]
  slideChange: [index: number]
}>()

// 响应式数据
const banners = ref<Banner[]>([])
const loading = ref(false)
const router = useRouter()

// 获取轮播图数据
const fetchBanners = async () => {
  try {
    loading.value = true
    let response

    if (props.position === 1) {
      response = await bannerApi.getHomeBanners(props.limit)
    } else {
      response = await bannerApi.getBannersByPosition(props.position, props.limit)
    }

    banners.value = response.data?.banners || []
  } catch (error) {
    console.error('获取轮播图失败:', error)
    ElMessage.error('获取轮播图失败')
  } finally {
    loading.value = false
  }
}

// 处理轮播图点击
const handleBannerClick = async (banner: Banner) => {
  try {
    // 记录点击事件
    await bannerApi.recordBannerClick(banner.id)

    // 触发自定义事件
    emit('bannerClick', banner)

    // 处理跳转
    if (banner.linkUrl) {
      if (banner.linkUrl.startsWith('http')) {
        window.open(banner.linkUrl, '_blank')
      } else {
        router.push(banner.linkUrl)
      }
    }
  } catch (error) {
    console.error('处理轮播图点击失败:', error)
  }
}

// 处理轮播切换
const handleSlideChange = (index: number) => {
  emit('slideChange', index)
}

// 处理图片加载错误
const handleImageError = (event: Event) => {
  const img = event.target as HTMLImageElement
  img.src = '/placeholder-banner.jpg' // 设置默认图片
}

// 组件挂载时获取数据
onMounted(() => {
  fetchBanners()
})

// 暴露刷新方法
defineExpose({
  refresh: fetchBanners
})
</script>

<style scoped>
.banner-container {
  position: relative;
  width: 100%;
}

.banner-item {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.banner-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.banner-item:hover .banner-image {
  transform: scale(1.05);
}

.banner-content {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: linear-gradient(transparent, rgba(0, 0, 0, 0.7));
  color: white;
  padding: 40px 30px 30px;
}

.banner-title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 10px;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.5);
}

.banner-description {
  font-size: 16px;
  line-height: 1.5;
  opacity: 0.9;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
}

.banner-loading,
.banner-empty {
  width: 100%;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .banner-content {
    padding: 20px 15px 15px;
  }

  .banner-title {
    font-size: 18px;
  }

  .banner-description {
    font-size: 14px;
  }
}

/* Element Plus 轮播图样式覆盖 */
:deep(.el-carousel__indicator) {
  background-color: rgba(255, 255, 255, 0.5);
}

:deep(.el-carousel__indicator.is-active) {
  background-color: #409eff;
}

:deep(.el-carousel__arrow) {
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
}

:deep(.el-carousel__arrow:hover) {
  background-color: rgba(0, 0, 0, 0.7);
}
</style>
